package com.youhong.teethcare;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.youhong.teethcare.adapter.ScanDeviceAdapter;
import com.youhong.teethcare.services.Common;
import com.youhong.teethcare.utils.Tools;

public class DeviceListActivity extends Activity implements ListView.OnItemClickListener, View.OnClickListener {

    ScanDeviceAdapter deviceAdapter;
    ListView lv;
    RelativeLayout ll1;
    Button btn_cancel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_list);
        adjustLayoutParams();
        getViews();
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        deviceAdapter = new ScanDeviceAdapter(this, null);

        BluetoothDevice device = getIntent().getParcelableExtra("device");
        int rssi = getIntent().getIntExtra("rssi", 0);
        lv.setAdapter(deviceAdapter);
        deviceAdapter.addDevice(device, rssi, device.getName(), "1741");

        startScan(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        startScan(false);
    }

    Handler mHandler = new Handler();
    boolean isScanning = false;

    BluetoothAdapter mBluetoothAdapter = null;

    private void getViews() {
        btn_cancel = findViewById(R.id.deviceList_btn);
        btn_cancel.setOnClickListener(this);

        lv = findViewById(R.id.deviceList_lv);
        lv.setOnItemClickListener(this);
        ll1 = findViewById(R.id.deviceList_ll1);
    }

    private void adjustLayoutParams() {

        int height = getWindowManager().getDefaultDisplay().getHeight();
        int width = getWindowManager().getDefaultDisplay().getWidth();

        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.gravity = Gravity.CENTER;
        params.height = (int) (height * 0.6f);
        params.width = (int) (width * 0.9f);
    }


    private void startScan(boolean enable) {
        // TODO Auto-generated method stub
        if (enable) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    isScanning = false;
                   /* bt_cancle.setText(getResources().getString(
                            R.string.start_scan));*/
                }
            }, 20000);
            deviceAdapter.clear();
            mBluetoothAdapter.startLeScan(mLeScanCallback);
            isScanning = true;
        /*    if (bt_cancle != null) {
                bt_cancle.setText(getResources().getString(R.string.stop_scan));
            }*/
        } else {
          /*  deviceDialog.dismiss();
            bt_cancle.setText(getResources().getString(R.string.start_scan));
           */
            mHandler.removeCallbacksAndMessages(null);
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            isScanning = false;
        }
    }

    private static final String TAG = "DeviceListActivity";

    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {

            final String dev_name = Tools.decodeDeviceName(scanRecord);

            Log.i(TAG, "onLeScan: "+dev_name);
            if (dev_name != null && (dev_name.toLowerCase().contains("1741") ||  dev_name.toLowerCase().contains("1835") || dev_name.toLowerCase().contains("agu")
                    || dev_name.toLowerCase().contains("j2058")|| dev_name.toLowerCase().contains("j2002a")|| dev_name.toLowerCase().contains("j2002")|| dev_name.toLowerCase().contains("fg"))) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        deviceAdapter.addDevice(device, rssi, dev_name, "1741");
                    }
                });
            }
        }
    };

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        BluetoothDevice device = deviceAdapter.getItem(position);


        //连接成功后，再保存设备信息
        /*Common.userInfo.setMac(device.getAddress());
        Common.userInfo.setDeviceName(device.getName());
        Common.userInfo.SyncToLocal(getApplicationContext());
        */

        startScan(false);
        Intent return_intent = new Intent();
        return_intent.putExtra("device", device);
        setResult(Activity.RESULT_OK,return_intent);
        this.finish();
    }

    @Override
    public void onClick(View v) {

        if (v == btn_cancel) {
            this.finish();
        }

    }
}
